
// import Loading from './Loading'
// import { aesEncrypt, aesDecrypt, aesKey } from "./AESTool";
// import { rsaDecrypt, rsaEncrypt } from "./RSATool";
import {
    Platform,
} from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Constant from './Constant'
import AndroidModule from "./AndroidConnent";
import resCode from './ResCode'

// import Localapi from "../../localapi";

const isIos = Platform.OS == 'ios';
let agent = ''
let tokenExpireCode = '401'

// let urlhost;
// if (__DEV__) {
//       urlhost = 'https://api-dev.shuaiche.com/';
//     // urlhost = 'https://api-test.shuaiche.com/';
//     //    urlhost = 'https://api.hx2car.com/';
// } else {
//     urlhost = 'https://api.shuaiche.com/';
// }

/**
 * GET 请求时，拼接请求URL
 * @param url 请求URL
 * @param params 请求参数
 * @returns {*}
 */
const handleUrl = url => params => {
    /*
    开发环境判断
    */

    params = {
        ...params,
    }
    if (params) {
        let paramsArray = []
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key])))
        if (url.search(/\?/) === -1 && url.length > 0) {
            typeof (params) === 'object' ? url += '?' + paramsArray.join('&') : url
        } else {
            url += '&' + paramsArray.join('&')
        }
    }
    return url
}

const formatHeader = ()=> {
    let header = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'version': DeviceInfo.getVersion(),
        "source": isIos ? '15' : '14',   //14安卓 15iOS
        "user-session-id": Constant.sessionId ? Constant.sessionId:''
    }
    return header;
}

//一个 Promise 就是一个代表了异步操作最终完成或者失败的对象
export default class HttpUtils {

    /**
     * 基于fetch 封装的GET 网络请求
     * @param url 请求URL
     * @param params 请求参数
     * @returns {Promise}
     */
    static getRequest = (url, params = {}, errorResponse = false) => {

        let header = formatHeader()

        if (Constant.userInfo.userId && !params.userId) {
            params.userId = Constant.userInfo.userId;
        }

        var baseDomain = Constant.apiDomain;

        // 判断url 是否在 Localapi.js 中
        // if (Localapi[url]) {
        //     console.log('GET请求本地地址 =',Localapi[url])
        //     baseDomain = Localapi[url]
        // }

        return new Promise(((resolve, reject) => {
            fetch(handleUrl(baseDomain + url)(params), {
                method: 'GET',
                headers: header
            })
                .then(response => {
                    // console.log('response.status = ',response.status)
                    return response.json()
                })//把数据解析成json格式,然后取出
                .then(result => {
                    // Loading.hide();
                    // 判断url 是否包含 getUserCarPurchaseNoViewCount
                    // console.log('url = ', url)
                    if (__DEV__ && url !== '/stockprod/carPurchaseProd/getUserCarPurchaseNoViewCount') {
                        console.log('start<<<<<<<<<<')
                        console.log('method = GET', 'url = ' + handleUrl(baseDomain + url)(params), 'header = ' + JSON.stringify(header), 'body = ', JSON.stringify(params))
                        console.log('result=',JSON.stringify(result))
                        console.log('>>>>>>>>>>end')
                    }

                    resCode(result, resolve, false)
                })
                .catch(error => {
                    // Loading.hide();
                    if (__DEV__) {
                        console.log('start<<<<<<<<<<')
                        console.log('method = GET', 'url = ' + handleUrl(baseDomain+ url)(params), 'header = ' + JSON.stringify(header), 'body = ', JSON.stringify(params))
                        console.log('error = ', error);
                        console.log('>>>>>>>>>>end')
                    }
                    reject(error);//表示失败
                })
        })
        )
    };

    //url中只包含接口名
    static postRequest = (url, params = {}) => {

        let header = formatHeader()

        if (Constant.userInfo.userId && !params.userId) {
            params.userId = Constant.userInfo.userId;
        }

        let baseDomain = Constant.apiDomain;

        // 判断url 是否在 Localapi.js 中
        // if (Localapi[url]) {
        //     console.log('POST本地地址 =',Localapi[url])
        //     baseDomain = Localapi[url]
        // }

        return new Promise(((resolve, reject) => {
            fetch(baseDomain + url, {
                method: 'POST',
                headers: header,
                body: JSON.stringify(params),//
            })//返回 服务器处理的结果
                .then(response => {
                    // console.log('response.status = ',response.status)
                    return response.json()
                })
                .then(result => {
                    // result = JSON.parse(result);
                    // console.log('Constant.apiDomain =',Constant.apiDomain )
                    if (__DEV__ && url !== '/tradeprod/quotation/getUserConversation') {
                        console.log('start<<<<<<<<<<')
                        console.log('method = POST', 'url = ', baseDomain + url, 'header = ' + JSON.stringify(header), 'body = ', JSON.stringify(params), 'result = ', JSON.stringify(result))
                        console.log('>>>>>>>>>>end')
                    }

                    resCode(result, resolve, false)
                })
                .catch(error => {
                    if (__DEV__) {
                        console.log('start<<<<<<<<<<')
                        console.log('method = POST', 'url = ', baseDomain + url, 'header = ' + JSON.stringify(header), 'body = ', JSON.stringify(params))
                        console.log('error = ', error);
                        console.log('>>>>>>>>>>end')
                    }
                    reject(error);
                })
        })
        )
    }
}
